package com.qf.ticketdemo.controller;

import com.qf.ticketdemo.mapper.TicketMapper;
import com.qf.ticketdemo.pojo.Ticket;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.spring.boot.CuratorZkTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ticket")
public class TicketController {

    @Autowired
    private CuratorZkTemplate template;

    @Autowired
    private TicketMapper ticketMapper;

    private String LOCK_PREFEX = "/LOCK:ZK:TICKET:ID:";

    @Value("${winnum}")
    private String winnum;

    @GetMapping("/sell/{id}")
    public void sell(@PathVariable("id") Integer id) throws Exception {

        while (true){

            //获取zk分布式锁
            String lockName = LOCK_PREFEX + id;
            InterProcessLock lock = template.getSharedReentrantLock(lockName);

            try {
                //加锁
                lock.acquire();
                //先判断是否有票
                Ticket ticket = ticketMapper.selectById(id);
                Integer count = ticket.getCount();
                if (count > 0) {
                    //卖
                    System.out.println(winnum + "正在卖第" + count + "张票");

                    //模拟卖一张票耗时1s
                    Thread.sleep(1000);

                    //更新数据库
                    ticket.setCount(count - 1);
                    ticketMapper.updateById(ticket);
                } else {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //释放锁
                lock.release();
            }
        }
    }
}
